package com.zhentao.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.common.constants.WemediaConstants;
import com.zhentao.mapper.WmMaterialMapper;
import com.zhentao.mapper.WmNewsMapper;
import com.zhentao.mapper.WmNewsMaterialMapper;
import com.zhentao.model.common.dtos.PageResponseResult;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemedia.dto.WmNewsDto;
import com.zhentao.model.wemedia.dto.WmNewsPageReqDto;
import com.zhentao.model.wemedia.pojo.WmMaterial;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.model.wemedia.pojo.WmNewsMaterial;
import com.zhentao.service.WmNewsAutoScanService;
import com.zhentao.service.WmNewsService;
import com.zhentao.utils.common.WmUserThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Date 2024/5/13 10:23
 * @Author xdm
 **/
@Service
public class WmNewsServiceImpl implements WmNewsService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;


    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.检查查询
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.把参数封装一下
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //3.补全属性
        wmNews.setUserId(WmUserThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setEnable((short) 1);
        //提交时间
        if (dto.getStatus() == 1) {
            wmNews.setSubmitedTime(new Date());
        }

        //4.获取文章的封面
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            //前端传递的是一个集合，数据库里面需要的时候字符串 用,隔开
            String images = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(images);
        }

        // 处理 tinyint 不能是负数   -1 --》  4
        if (dto.getType() == WemediaConstants.WM_NEWS_TYPE_AUTO) {
            dto.setType((short) 4);
            wmNews.setType((short) 4);
        }

        //5.添加数据库
        //判断是新增操作还是修改操作
        if (dto.getId() == null) {  //新增
            wmNewsMapper.insert(wmNews);
        } else {  //修改操作  -需要删除素材与内容/封面的关系

            //删除关联关系
            Integer newsId = dto.getId();
            QueryWrapper<WmNewsMaterial> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(WmNewsMaterial::getNewsId, newsId);
            wmNewsMaterialMapper.delete(queryWrapper);
            //修改
            wmNewsMapper.updateById(wmNews);

        }

        //新增关联
        //处理封面    封面是自己上传的  /封面是自动获取的
        if (dto.getType() != 4) {  //图片是自己上传的
            List<String> images = dto.getImages();
            //把url转换成id

            List<Integer> mids = new ArrayList<>();
            for (String img : images) {
                QueryWrapper<WmMaterial> materQ = new QueryWrapper();
                materQ.lambda().eq(WmMaterial::getUrl, img);
                WmMaterial wmMaterial = wmMaterialMapper.selectOne(materQ);
                mids.add(wmMaterial.getId());
            }

            //把关系维护进去
            wmNewsMaterialMapper.saveRelations((short) 1, wmNews.getId(), mids);

        } else {  //自动获取封面
            //如何自动获取到封面  从内容里面获取
            /**
             * {
             *     type:"text",value:"34435"
             * }
             * {type:"image",value:"url"}
             */
            List<String> images = new ArrayList<>();

            List<Map> maps = JSON.parseArray(dto.getContent(), Map.class);
            for (Map map : maps) {
                //传递过来是个图片
                if (map.get("type").equals("image")) {
                    //把获取到的图片保存到images里面 -list集合
                    images.add((String) map.get("value"));
                }

            }

            if (images.size() == 0) {  //内容里面是没有图片的
                //没有图片的  页面是没有4的局部的  0  1  3；   没有图片，布局就是0
                // wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);

                WmNews wmNews1 = new WmNews();
                wmNews1.setId(wmNews.getId());
                wmNews1.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                wmNewsMapper.updateById(wmNews1);
            } else {  //内容里面是有图片的   把图片设置成封面
                // size=1  type=1  size=2 type=1 size=3 type=3 size=4 type=3
                //有图片的
                if (images.size() == 1) {
                    //修改type=1
                    WmNews wmNews1 = new WmNews();
                    wmNews1.setId(wmNews.getId());
                    wmNews1.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);

                    //1.news表里面得images字段
                    String newsImages = StringUtils.join(images, ",");
                    wmNews1.setImages(newsImages);
                    wmNewsMapper.updateById(wmNews1);

                    List<Integer> mids = new ArrayList<>();
                    for (String img : images) {
                        //2.处理素材与news的关系
                        QueryWrapper<WmMaterial> materQ = new QueryWrapper();
                        materQ.lambda().eq(WmMaterial::getUrl, img);
                        WmMaterial wmMaterial = wmMaterialMapper.selectOne(materQ);
                        mids.add(wmMaterial.getId());

                    }
                    //把关系维护进去
                    wmNewsMaterialMapper.saveRelations((short) 1, wmNews.getId(), mids);
                }

            }

        }



        //处理内容与素材直接的关系  从里面里面吧素材获取到url -- id  添加操作
        if(dto.getStatus()==1){
            wmNewsAutoScanService.autoScanWnMews(wmNews.getId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {


        //1.检查参数
        dto.checkParam();
        //2.分页查询
        IPage page = new Page(dto.getPage(), dto.getSize());

        QueryWrapper<WmNews> queryWrapper = new QueryWrapper<>();
        //select xxx from xx where userid=1  if(channelId!=null){and   channelId=null }
        //1.userId
        queryWrapper.lambda().eq(WmNews::getUserId, WmUserThreadLocalUtil.getUser().getId());
        //2.频道
        queryWrapper.lambda().eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //3.状态
        queryWrapper.lambda().eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //4关键字
        queryWrapper.lambda().eq(dto.getKeyword() != null, WmNews::getLabels, dto.getKeyword());

        //5.时间范围
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {

            queryWrapper.lambda().between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }

        page = wmNewsMapper.selectPage(page, queryWrapper);

        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), Integer.valueOf(page.getTotal() + ""));

        responseResult.setCode(200);
        responseResult.setErrorMessage("请求成功");
        responseResult.setData(page.getRecords());


        return responseResult;
    }
}